package com.yuexiao.controller;

import com.yuexiao.entity.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName:CommonController
 * @Auther: YUEXIAO
 * @Description: 通用控制器
 * @Date: 2022/8/12 10:19
 * @Version: v1.0
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    //获取存储路径
    @Value("${culiang.path}")
    private String basePath;

    /**
     * 上传图片
     *
     * @param file MultipartFile 上传的文件流
     * @return ResultInfo 返回结果对象
     */
    @RequestMapping("/upload")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public ResultInfo upload(MultipartFile file) {

        if (file == null) {
            return ResultInfo.error("上传内容为空");
        }

        log.info(file.toString());

        //获取原始文件名后缀
        String oldName = file.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));

        //使用UUID生成新的文件名
        String newName = UUID.randomUUID() + suffix;

        //创建一个目录对象
        File dir = new File(basePath);
        //判断路径是否存在，不存在则创建
        if (!dir.exists()) {
            //创建路径
            dir.mkdirs();
        }

        //将临时文件转移到指定位置
        try {
            file.transferTo(new File(basePath + newName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResultInfo.success(newName);
    }


    /**
     * 图片下载回显
     *
     * @param name     String 文件名
     * @param response
     */
    @GetMapping("download")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public void download(String name, HttpServletResponse response) throws Exception {

        //通过输入流读取文件
        FileInputStream fileInputStream = new FileInputStream(basePath + name);
        //输出流，通过输出流将文件写回浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        //关闭资源
        outputStream.close();
        fileInputStream.close();

    }

}
